from flask import Flask, request, jsonify
import mysql.connector
import json

app = Flask(__name__)

# 连接数据库
config = {
    'user': 'root',
    'password': 'ys_nj_sst!',
    'host': '127.0.0.1',
    'database': 'new_ys_wms',
    'raise_on_warnings': True
}


@app.route('/api/answer', methods=['GET'])
def get_answer():
    # 获取用户请求中的问题
    # question = request.json.get('question')

    # 创建连接
    conn = mysql.connector.connect(**config)

    # 创建cursor对象
    cursor = conn.cursor()

    # 执行查询
    cursor.execute("SELECT * FROM t_unint")

    result = cursor.fetchone()
    rows = cursor.fetchall()

    # 关闭数据库连接
    cursor.close()
    conn.close()

    # 返回结果
    if result:
        # 转json
        results = [{'id': row[0], 'unit': row[3], 'time':row[5].strftime('%Y-%m-%d %H:%M:%S')} for row in rows]
        # print(results)
        # 使用indent参数美化输出
        json_data = json.dumps(results, indent=2)
        return json_data
    else:
        return jsonify({'answer': '未找到相关答案'})


if __name__ == '__main__':
    app.run(debug=True)
